package com.woyou.component;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.jing.biandang.R;
import com.woyou.adapter.MultiSpinnerPopAdapter;

public class MultiSpinnerPopup {
	private Context c;
	private TextView positionView;
	private PopupWindow popupWindow;
	MultiSpinnerPopAdapter adapterSp;
	public MultiSpinnerPopup(Context context, TextView positionView,ArrayList<HashMap<String,Object>> data) {
		this.c = context;
		this.positionView = positionView;
		showPaoWindow(data);
	}
	
	// 弹出泡泡窗体
	public void showPaoWindow(final ArrayList<HashMap<String,Object>> arrayList) {
		// 实例化泡泡窗台的布局文件
		View contentView =LayoutInflater.from(c).inflate(R.layout.layout_multispinner, null);
		ListView layout_taskmanager_spinner_listview = (ListView) contentView.findViewById(R.id.layout_taskmanager_multispinner_listview);
		adapterSp = new MultiSpinnerPopAdapter(c, arrayList);
		layout_taskmanager_spinner_listview.setAdapter(adapterSp);
		// ListView控件点击事件
		layout_taskmanager_spinner_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				HashMap<String,Object> map=arrayList.get(position);
				boolean state=Boolean.parseBoolean(map.get("state").toString());
				CheckBox cb=(CheckBox)view.findViewById(R.id.item_taskmanager_multispinner_listview_cb);
				
				if(state){
					cb.setChecked(false);
					map.put("state",false);
				}else{
					cb.setChecked(true);
					map.put("state", true);
				}
				ArrayList<String> nameList=new ArrayList<String>();
				for(int i=0;i<arrayList.size();i++){
					if(Boolean.parseBoolean(arrayList.get(i).get("state").toString())){
						nameList.add(arrayList.get(i).get("name").toString());
					}
				}
				if(nameList.size()==0){
					positionView.setText(null);
				}else if(nameList.size()==1){
					positionView.setText(nameList.get(0));
				}else{
					String result=null;

						for(int j=0;j<nameList.size();j++){
							if(j==0){
								result=nameList.get(j);
							}else{
								result=result+","+nameList.get(j);
							}
						}

					positionView.setText(result);
				}
				adapterSp.notifyDataSetChanged();
			}
		});

		// 实例化泡泡窗体
		popupWindow = new PopupWindow(contentView,
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);

		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());

		// 显示泡泡窗体
		popupWindow.showAsDropDown(positionView, 0, 0);

	}
}
